/**
 * AI 聊天机器人核心类
 */
import { ChatOpenAI } from '@langchain/openai';
import { HumanMessage, AIMessage, SystemMessage, BaseMessage } from '@langchain/core/messages';
import { BufferMemory } from 'langchain/memory';
import { ConversationChain } from 'langchain/chains';
import { config } from './config.js';

export interface ChatbotOptions {
  systemPrompt?: string;
  temperature?: number;
  maxTokens?: number;
  enableMemory?: boolean;
}

export class AIChatbot {
  private model: ChatOpenAI;
  private memory?: BufferMemory;
  private chain?: ConversationChain;
  private conversationHistory: BaseMessage[] = [];
  private enableMemory: boolean;

  constructor(options: ChatbotOptions = {}) {
    this.enableMemory = options.enableMemory ?? true;

    // 初始化通义千问模型（使用 OpenAI 兼容接口）
    this.model = new ChatOpenAI({
      modelName: config.modelName,
      temperature: options.temperature ?? config.temperature,
      maxTokens: options.maxTokens ?? config.maxTokens,
      openAIApiKey: config.apiKey,
      configuration: {
        baseURL: config.baseURL,
      },
    });

    // 如果有系统提示词，添加到历史记录
    if (options.systemPrompt) {
      this.conversationHistory.push(new SystemMessage(options.systemPrompt));
    }

    // 初始化记忆（如果启用）
    if (this.enableMemory) {
      this.memory = new BufferMemory({
        returnMessages: true,
        memoryKey: 'history',
      });

      this.chain = new ConversationChain({
        llm: this.model,
        memory: this.memory,
      });
    }
  }

  /**
   * 发送消息并获取回复
   */
  async chat(message: string): Promise<string> {
    if (this.enableMemory && this.chain) {
      // 使用 ConversationChain（自动管理记忆）
      const response = await this.chain.call({ input: message });
      return response.response;
    } else {
      // 手动管理对话历史
      this.conversationHistory.push(new HumanMessage(message));
      const response = await this.model.invoke(this.conversationHistory);
      this.conversationHistory.push(new AIMessage(response.content as string));
      return response.content as string;
    }
  }

  /**
   * 流式输出（实时响应）
   */
  async *chatStream(message: string): AsyncGenerator<string> {
    this.conversationHistory.push(new HumanMessage(message));
    
    const stream = await this.model.stream(this.conversationHistory);
    let fullResponse = '';

    for await (const chunk of stream) {
      const content = chunk.content as string;
      fullResponse += content;
      yield content;
    }

    this.conversationHistory.push(new AIMessage(fullResponse));
  }

  /**
   * 获取对话历史
   */
  getHistory(): BaseMessage[] {
    return this.conversationHistory;
  }

  /**
   * 清空对话历史
   */
  clearHistory(): void {
    const systemMessages = this.conversationHistory.filter(
      msg => msg._getType() === 'system'
    );
    this.conversationHistory = systemMessages;
    
    if (this.memory) {
      this.memory.clear();
    }
  }

  /**
   * 获取记忆中的对话摘要
   */
  async getMemorySummary(): Promise<string> {
    if (!this.memory) {
      return '未启用记忆功能';
    }
    
    const memoryVars = await this.memory.loadMemoryVariables({});
    return JSON.stringify(memoryVars, null, 2);
  }
}

